<?php
namespace app\controller;

use app\BaseController;
use think\facade\View;
use app\model\Lists;
use think\Request;
use app\validate\ListsValidate;
use think\exception\ValidateException;

use Endroid\QrCode\Color\Color;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelLow;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Label\Label;
use Endroid\QrCode\Logo\Logo;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin;
use Endroid\QrCode\Writer\PngWriter;


class Index extends BaseController
{
	/**
	 * @var \think\Request Request实例
	 */
	protected $request;
	
	/**
	 * 构造方法
	 * @param Request $request Request对象
	 * @access public
	 */
	public function __construct(Request $request)
	{
		$this->request = $request;
	}
	
	/* INDEX */
    public function index($domain='',$type='')
    {
        
		if ($type=='api' and $domain=='') {
		    return json([
				'code'=>404,
				'msg'=>'目标链接不存在！'
			]);
		}elseif ($domain=='') {
			$domain = $_SERVER['HTTP_HOST'];
		}
		
		$Lists = new Lists();
		
		$target_url = $Lists::where('from_url',$domain)->findOrEmpty();
        if ($target_url->isEmpty()) {
        	return json([
				'code'=>4041,
				'msg'=>'目标链接不存在！'
			]);
        }
		
		$Lists->where('id',$target_url['id'])->inc('view')->update();
		if ($type=='api') {
			return json([
				'code'=>200,
				'target'=>$target_url['to_url']
			]);
		}
		//dump($target_url['to_url']);exit;
		View::assign('target_url',$target_url['to_url']);
		return View::fetch();
		//echo '';
		//header("Location: ".$target_url['to_url']);
    }
	
	/* 表单提交 */
	public function add(Request $request) {
		//$check = $request->checkToken('__token__');
		$check=true;
		if(false === $check) {
			return json([
				'code'=>5021,
				'msg'=>'添加失败，令牌失效！'
			]);
		}
		try {
			validate(ListsValidate::class)->check($request->post());
		} catch (ValidateException $e) {
			// 验证失败 输出错误信息
			return json([
				'code'=>5020,
				'msg'=>'数据格式验证失败！'
			]);
		}
		$data = $request->post();
		// 需要生成二维码的内容 
		$urls = 'http://'.$data['from_url'];
		$data['img']=$this->qrCode($urls,$data['ename']);
		$Lists = new Lists();
		
		try {
			if ($data['id']!='' or !empty($data['id'])) {
				$update=$Lists->find($data['id']);
				$update->allowField(['nickname','ename','from_url','to_url','status','img'])->save($data);
			} else {
				$Lists->allowField(['nickname','ename','from_url','to_url','status','img'])->save($data);
			}
			
			return json([
				'code'=>200,
				'msg'=>'操作成功！'
			]);
		} catch (\Throwable $th) {
			return json([
				'code'=>5022,
				'msg'=>'数据添加失败！'
			]);
		}
		
	}
	
	
	
	/* 管理链接 */
	public function gl($passwd=''){
		if ($passwd!='123456') {
			return json(['code'=>'403','msg'=>'无权使用本链接！']);
		}
		
		return View::fetch();
	}
	
	/* 数据列表 */
	public function getList(){
		$Lists = new Lists();
		$data=$Lists->where('status',1)->order('create_time','desc')->select();
		if ($data) {
			$count=count($data);
		} else {
			$count=0;
		}
		
		$list_data=[
			 "code"=>0,
			  "msg"=>"",
			  "count"=>$count,
			  "data"=>$data
		];
		return json($list_data);
	}
	
	/* 数据操作 */
	public function ac(string $ac='detail', $ids='') {
		if ($ids=='') {
			return json([
				'code'=>404,
				'msg'=>'数据不存在'
			]);
		}
		$data=$this->request->param();
		$Lists = new Lists();
		try {
			switch ($ac) {
				case 'del':
					// 删除
					$Lists::destroy($ids);
					break;
				case 'edit':
					// 编辑
					if (count($data)==0) {
						# code...
					} else {
						# code...
					}
					
					$this->add($request);
					break;
				
				default:
					// 查看
					$data=$Lists->find($ids);
					return json([
						'code'=>200,
						'msg'=>'操作成功！',
						'data'=>$data
					]);
					break;
			}
			return json([
				'code'=>200,
				'msg'=>'操作成功！'
			]);
		} catch (\Throwable $th) {
			return json([
				'code'=>5021,
				'msg'=>'操作失败'
			]);
		}
		
		
	}
	
	
	/**
	     * 生成二维码
	     * @param string $url [字符]
	     * @param  [type] $is_save [是否保存]
	     * @param  [type] $pid     [唯一标识符]
	     * @return string  [type]  [返回图片标签字符串]
	     */
	    public function qrCode(string $url = '',string $label_name='', $is_save = true, $pid = 0)
	    {
	        $writer = new PngWriter();
	        $qrCode = QrCode::create($url)//跳转的url地址
	        ->setEncoding(new Encoding('UTF-8'))    //设置编码格式
	        ->setErrorCorrectionLevel(new ErrorCorrectionLevelLow())    //设置纠错级别为低
	        ->setSize(200)      //大小
	        ->setMargin(20)     //边距
	        ->setRoundBlockSizeMode(new RoundBlockSizeModeMargin())     //设置圆轮大小边距
	        ->setForegroundColor(new Color(0, 0, 0))        //前景色
	        ->setBackgroundColor(new Color(255, 255, 255));       //背景色
	        $logo = Logo::create(app()->getRootPath() .'/public/static/logo.jpg')             //logo的照片路径
	            ->setResizeToWidth(20);                 //logo的大小
	        $label = Label::create($label_name)      //二维码下面的文字
	        ->setTextColor(new Color(0, 0, 0)); //文字的颜色
	        $result = $writer->write($qrCode, $logo, $label);
			
	        header('Content-Type: '.$result->getMimeType());
	        $result->getString();
	        if(!$is_save){
	            $dataUri = $result->getDataUri();       //DATA－URI 是指可以在Web 页面中包含图片但无需任何额外的HTTP 请求的一类URI.
	            //return "<img src='$dataUri' alt='测试二维码'>";
				return $dataUri;
	        }
	        $file_path = app()->getRootPath() . env('QRCODE_PATH');
	        if(!file_exists($file_path)){
	            mkdir($file_path,0777,true);
	        }
			
	        $qrcode='qrcode_'.time().mt_rand(1,9).'.png';   //二维码文件名称,mt_rand()运行速度要比rand()快很多
			
	        $result->saveToFile($file_path.$qrcode);
			$imgs=str_replace("public", '', env('QRCODE_PATH').$qrcode);
	        return $imgs;
	    }
}
